<?php

namespace App\Service;

use App\Models\Call;
use App\Models\Cdr;
use App\Models\Gateway;
use App\Models\Queue;
use App\Models\Sip;
use App\Models\Task;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class CallcenterListenBleg
{
    //通话记录对象
    public $call;
    public $sip;
    public $fs;

    public function __construct($call, $sip)
    {
        $this->call = $call;
        $this->sip = $sip;
        $this->fs = new SwooleFreeswitch();
        if (!$this->fs->connect()) {
            return false;
        }

    }

    public function run()
    {
        $record_url = config('freeswitch.record_url');
        $fs_dir = '/usr/local/freeswitch';

        //设置呼叫分机的uuid
        $this->call->update([
            'bleg_uuid' => uuid_generate(),
        ]);

        $varStr = "{origination_uuid=" . $this->call->bleg_uuid . "}";
        $varStr .= "{origination_caller_id_number=" . $this->call->phone . "}";
        $varStr .= "{origination_caller_id_name=" . $this->call->phone . "}";
        $dail_string = "originate " . $varStr . "user/" . $this->sip->username." &echo()";

        $this->sip->update(['state'=>'ringing']);
        $this->fs->bgapi($dail_string);
        $this->fs->events("CHANNEL_ANSWER CHANNEL_HANGUP_COMPLETE");
        $this->fs->filteruuid($this->call->bleg_uuid);

        while (true) {
            $filepath = $fs_dir . '/recordings/' . date('Y/m/d/');
            $received_parameters = $this->fs->recvEvent();
            if (!empty($received_parameters)) {
                $json = $this->fs->serialize($received_parameters);
                $eventname = Arr::get($json, 'Event-Name', null);
                switch ($eventname) {
                    case 'CHANNEL_ANSWER':
                        //修改分机状态
                        $this->sip->update(['state'=>'active']);
                        //桥接AB
                        $res = $this->fs->api("uuid_bridge " . $this->call->aleg_uuid . " " . $this->call->bleg_uuid);
                        //桥接失败挂断B，此时A已挂断才导致桥接失败
                        if (!Str::startsWith($res, "+OK")) {
                            $this->fs->bgapi("uuid_kill", $this->call->bleg_uuid);
                            $this->fs->disconnect();
                            $this->sip->update(['state'=>'down']);
                            break 2;
                        }
                        //开启全程录音
                        $fullfile = $filepath . 'callcenter_' . $this->call->bleg_uuid . '.wav';
                        $this->fs->bgapi("uuid_record {$this->call->bleg_uuid} start {$fullfile} 7200");
                        $this->call->update([
                            'datetime_sip_answer' => date('Y-m-d H:i:s'),
                            'status' => 4,
                            'sip_id' => $this->sip->id,
                            'sip_username' => $this->sip->username,
                            'record_file' => str_replace($fs_dir, $record_url, $fullfile),
                        ]);
                        break;
                    case 'CHANNEL_HANGUP_COMPLETE':
                        $this->call->refresh();
                        if ($this->call->datetime_end == null){
                            $billsec = $this->call->datetime_sip_answer ? time() - strtotime($this->call->datetime_sip_answer) : 0;
                            $this->call->update([
                                'datetime_end' => date('Y-m-d H:i:s'),
                                'status' => 4
                            ]);
                        }
                        Queue::query()->where('call_id',$this->call->id)->delete();
                        $this->sip->update(['state'=>'down']);
                        break 2;
                    default:
                        break;
                }
            }
        }
        $this->fs->disconnect();
    }

}
